package com.ruoyi.project.rate.service;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.framework.web.service.CrudService;
import com.ruoyi.project.rate.Constants;
import com.ruoyi.project.rate.domain.Attach;
import com.ruoyi.project.rate.domain.Scene;
import com.ruoyi.project.rate.domain.SceneTrack;
import com.ruoyi.project.rate.mapper.SceneMapper;
import com.ruoyi.project.system.dict.service.IDictDataService;

@Service
public class SceneService extends CrudService<SceneMapper, Scene> {
	@Autowired
	private SceneMapper sceneMapper;
	@Autowired
	private SceneTrackService sceneTrackService;
	@Autowired
	private IDictDataService dictDataService;
	@Autowired
	private AttachService attachService;

	@Transactional(readOnly = false)
	public void saveScene(Scene scene) {
		super.save(scene);
		this.addTrack(scene, "保存", "提交成功");

		// update attach
		if ("1".equals(scene.getAttachChangeFlag())) {
			if (scene.getAttachIds() == null) {
				scene.setAttachIds(new String[] {});
			}
			if (scene.getAttachIds() != null) {
				int order = 1;
				for (String attachId : scene.getAttachIds()) {
					Attach a = new Attach(attachId);
					a.setRelId(scene.getId());
					a.setOrderNum(order++);
					this.attachService.updateRelId(a);
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("relId", scene.getId());
			map.put("attachIdList", Arrays.asList(scene.getAttachIds()));
			this.attachService.deleteByRelIdAndNotIn(map); // 删除无相关记录
		}
	}

	public List<Scene> checkList(Scene scene) {
		return this.sceneMapper.checkList(scene);
	}
	
	/**
	@Transactional(readOnly = false)
	public int submitToCheck(Scene scene) {
		scene.setStatus(Constants.SCENE_STATUS_CHECK1);
		
		int i = this.sceneMapper.updateStatus(scene);
		
		this.addTrack(scene, "提交政治处审批", "提交政治处审批成功");
		return i;
	}
	**/
	
	/**
	@Transactional(readOnly = false)
	public int batchSubmitToCheck(Sup sup, String ids) {
		int checkedCount = 0;
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			Sup _sup = this.get(id);
			if (_sup == null) {
				continue;
			}
			
			if (!StringUtils.equalsAny(_sup.getStatus(),
					Constants.KH_STATUS_DRAFT,
					Constants.KH_STATUS_REJECTED)) {
				continue;
			}
			
			this.submitToCheck(_sup);
			checkedCount++;
		}
		
		return checkedCount;
	}
	**/
	
	@Transactional(readOnly = false)
	public void submitCheck(Scene scene) {
		String pageFlag = scene.getPageFlag();
		
		String operation = dictDataService.selectDictLabel(
				Constants.SCENE_STATUS, pageFlag);
		if (StringUtils.isBlank(operation)) {
			throw new RuntimeException("error operation[submitCheck]");
		}
		
		String next = null;
		if (Constants.SCENE_STATUS_CHECK10.equals(pageFlag)) {
			next = Constants.SCENE_STATUS_CHECK20;
			
			// 如果当前用户具有jyz角色，则直接审核通过
			/**
			Set<String> selectRoleKeys = this.roleService.selectRoleKeys(ShiroUtils.getSysUser().getUserId());
			if (selectRoleKeys.contains("jyz") || selectRoleKeys.contains("JYZ")) {
				next = Constants.SCENE_STATUS_APPROVED;
			}
			**/
		} else if (Constants.SCENE_STATUS_CHECK20.equals(pageFlag)) {
			next = Constants.SCENE_STATUS_APPROVED;
		}
		
		if (StringUtils.isBlank(next)) {
			throw new RuntimeException("error next status[submitCheck]");
		}
		
		if (Constants.SCENE_STATUS_APPROVED.equals(scene.getCheckResult())) {
			scene.setStatus(next);
		} else {
			scene.setStatus(Constants.SCENE_STATUS_REJECTED);
		}
		
		scene.setCheckTime(new Date());
		this.sceneMapper.submitCheck(scene);
		
		// 记录轨迹
		String result = Constants.SCENE_STATUS_APPROVED.equals(scene.getCheckResult()) ? "审核通过" : "审核不通过";
		this.addTrack(scene, operation, result + "，审核意见：" + scene.getCheckDesc());
	}
	
	@Transactional(readOnly = false)
	public int batchSubmitCheck(Scene scene, String ids) {
		int checkedCount = 0;
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			Scene _scene = this.get(id);
			if (_scene == null) {
				continue;
			}
			
			if (!StringUtils.equals(_scene.getStatus(), scene.getPageFlag())) {
				continue;
			}
			
			_scene.setPageFlag(scene.getPageFlag());
			_scene.setCheckResult(scene.getCheckResult());
			if (Constants.SCENE_STATUS_APPROVED.equals(_scene.getCheckResult())) {
				_scene.setCheckDesc("通过");
			} else {
				_scene.setCheckDesc("拒绝");
			}
			
			this.submitCheck(_scene);
			checkedCount++;
		}
		
		return checkedCount;
	}

	@Transactional(readOnly = false)
	public void cancelCheck(Scene scene) {
		String pageFlag = scene.getPageFlag();
		String operation = dictDataService.selectDictLabel(Constants.SCENE_STATUS, pageFlag);
		if (StringUtils.isBlank(operation)) {
			throw new RuntimeException("error operation[cancelCheck]");
		}
		operation += "-撤销";

		Scene exists = this.get(scene);
		if (exists == null) {
			throw new RuntimeException("查询不到记录.");
		}
		String currentStatus = exists.getStatus();
		boolean canCancelCheck = false;

		// 校验是否可撤回审核
		if (Constants.SCENE_STATUS_CHECK20.equals(pageFlag) && Constants.SCENE_STATUS_APPROVED.equals(currentStatus)) {
			canCancelCheck = true;
		} else if (Constants.SCENE_STATUS_CHECK10.equals(pageFlag) && Constants.SCENE_STATUS_CHECK20.equals(currentStatus)) {
			canCancelCheck = true;
		}

		if (!canCancelCheck) {
			throw new RuntimeException("当前状态不允许撤回审核.");
		}

		scene.setStatus(pageFlag);
		this.sceneMapper.updateStatus(scene);

		// 记录轨迹
		this.addTrack(scene, operation, null);
	}
	
    @Transactional(readOnly = false)
    public void cancelSubmit(Scene scene) {
    	String operation = null;
    	String currentStatus = scene.getStatus();
    	boolean canCancel = false;
    	
		if (Constants.SCENE_STATUS_CHECK10.equals(currentStatus)) {
			canCancel = true;
			operation = "撤回";
    		scene.setStatus(Constants.SCENE_STATUS_DRAFT);
		}
    	
    	if (!canCancel) {
    		throw new RuntimeException("不允许当前操作！");
    	}
    	
    	this.sceneMapper.updateStatus(scene); // 更新状态
    	
    	// 记录轨迹
    	this.addTrack(scene, operation, "撤回成功");
    }
	
	/**
    @Transactional(readOnly = false)
	public int batchCancel(Sup sup, String ids) {
		int checkedCount = 0;
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			Sup _sup = this.get(id);
			if (_sup == null) {
				continue;
			}
			
			if (!StringUtils.equals(_sup.getStatus(), Constants.KH_STATUS_KHZ)) {
				continue;
			}
			
			this.cancel(_sup);
			checkedCount++;
		}
		
		return checkedCount;
	}
	**/
    
	private void addTrack(Scene scene, String operation, String remark) {
		SceneTrack track = new SceneTrack();
		track.setScene(scene);
		track.setOperation(operation);
		track.setRemark(remark);
		track.setCurrentStatus(scene.getStatus());
		this.sceneTrackService.save(track);
	}
	
	/**
    @Transactional(readOnly = false)
    public int updateStatus(Sup sup) {
        return this.supMapper.updateStatus(sup);
    }
    **/
}
